﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using EncryptUtils;

namespace ACE
{
    public partial class FormConnect : Form
    {
        Controller controller;
        //DataEncryptor Encryption;

        public FormConnect(Controller c)
        {
            controller = c;
            InitializeComponent();
        }

        private void Connect_Load(object sender, EventArgs e)
        {
            GetConfigSettings();
        }

        private void GetConfigSettings()
        {
            if (!string.IsNullOrEmpty(controller.ControllerUrl))
            {
                textBoxControllerUrl.Text = controller.ControllerUrl;
                textBoxAccount.Text = controller.Account;
                textBoxUserName.Text = controller.UserName;
                textBoxPassword.Text = controller.Password;
            }
            else
            {
                textBoxControllerUrl.Text = @"https://myaccount.saas.appdynamics.com";
                textBoxAccount.Text = "customer1";
            }

        }

        private void Connect_FormClosing(object sender, FormClosingEventArgs e)
        {
            //In case windows is trying to shut down, don't hold the process up
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                return;
            }

            if (this.DialogResult == DialogResult.Cancel)
            {
                // Assume that X has been clicked and act accordingly.
                // Confirm user wants to close
                if (!controller.Authenticated)
                {
                    var changed = (textBoxControllerUrl.Text == controller.ControllerUrl &&
                        textBoxAccount.Text == controller.Account &&
                        textBoxUserName.Text == controller.UserName &&
                        textBoxPassword.Text == controller.Password) ? false : true;
                    if (changed)
                    {
                        switch (MessageBox.Show(this, "Controller connection not authenticated. Do you want to cancel?", "Controller Connection Not Authenticated", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            //Stay on this form
                            case DialogResult.No:
                                e.Cancel = true;
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            //if (string.Equals((sender as Button).Name, @"CloseButton"))
            //{
            //    // Do something proper to CloseButton.
            //}
            //else
            //{
            //    // Then assume that X has been clicked and act accordingly.
            //}
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            Authenticate();
        }

        private void Authenticate()
        {
            try
            {
                controller.ControllerUrl = textBoxControllerUrl.Text;
                controller.Account = textBoxAccount.Text;
                controller.UserName = textBoxUserName.Text;
                controller.Password = textBoxPassword.Text;
                controller.PortalLogin = checkBoxPortalLogin.Checked;
                if (checkBoxPortalLogin.Checked)
                {
                    //controller.AuthenticatePortal("https://login.appdynamics.com", "", controller.UserName, controller.Password, "sso/authenticate");
                    controller.AuthenticatePortal("https://portal.appdynamics.com", "", controller.UserName, controller.Password, "reports/saaslogin/139889694986TVZ");
                }
                controller.Authenticate();

                if (checkBoxRememberMe.Checked)
                {
                    SaveConfigSettings();
                }
                this.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Reason: " + e.Message, "Failed to authenticate.");
            }
        }

        private void SaveConfigSettings()
        {
            int i = 0;
            var controllerUrl = ConfigUtils.ReadSetting(string.Format("{0}_{1}", "ControllerUrl", i.ToString()), "");
            while (!string.IsNullOrEmpty(controllerUrl))
            {
                if (string.Equals(controllerUrl, controller.ControllerUrl, StringComparison.CurrentCultureIgnoreCase))
                {
                    break;
                }

                i++;
                controllerUrl = ConfigUtils.ReadSetting(string.Format("{0}_{1}", "ControllerUrl", i.ToString()), "");
            }

            ConfigUtils.AddUpdateAppSetting(string.Format("{0}_{1}", "ControllerUrl", i.ToString()), controller.ControllerUrl);
            ConfigUtils.AddUpdateAppSetting(string.Format("{0}_{1}", "Account", i.ToString()), controller.Account);
            ConfigUtils.AddUpdateAppSetting(string.Format("{0}_{1}", "Username", i.ToString()), controller.UserName);
            ConfigUtils.AddUpdateAppSetting(string.Format("{0}_{1}", "PortalLogin", i.ToString()), controller.PortalLogin ? "1": "0");
            string encryptedPassword = DE2.EncryptString(controller.Password, controller.UserName);
            ConfigUtils.AddUpdateAppSetting(string.Format("{0}_{1}", "Password", i.ToString()), encryptedPassword);
        }

    }
}
